package me.pinion.model;


import com.jfinal.plugin.activerecord.Model;
import me.pinion.Log
import me.pinion.service.CommentService;
import me.pinion.service.Service;

import java.lang.reflect.Field;
import java.util.List;

public abstract class XModel<M extends XModel<M>> extends Model<M> {

    CommentService commentService = Service.getInstance(CommentService.class)

    public XModel() {
        super();
        Field[] fields =this.getClass().getDeclaredFields();
        for (int i=0;i < fields.length; i++){
            Field field = fields[i];
            Class clazz = field.getType();
            if(Service.class.isAssignableFrom(clazz)){
                try {
                    this.setProperty(field.name, Service.getInstance(clazz))
                } catch (IllegalAccessException e) {
                    Log.e(e);
                }
            }
        }
    }

    public int getId() {
        try {
            return getLong("id").intValue();
        }catch (ClassCastException e){
            return getInt("id");
        }catch (NullPointerException e){
            return 0;
        }
    }

    public int getModelId() { return this.getModeType().getId(); }
    public ModelType getModeType() { return ModelType.dao.getByClass(this.getClass()); }

    public M reset(XModel<M> model) { return this.setAttrs(model.getAttrs()); }

    public List<Comment> getComments() { return commentService.recentByModel(this); }
    public List<Comment> getComments(int page) { return commentService.recentByModel(this, page, 20); }
    public List<Comment> getComments(int page, int pagesize) { return commentService.recentByModel(this, page, pagesize); }

    public Long getFavoCount() { return Favorite.dao.count(this); }
    public Long getLikeCount() { return Like.dao.count(this); }
    public Long getVisitCount() {
        if (this.getLong("visit_count") != null){
            return this.getLong("visit_count");
        }else {
            return Visit.dao.count(this);
        }
    }


    public List<Tag> getTags() { return this.getTags(3);}
    public List<Tag> getTags(int max) { return Tag.dao.top(this, max); }

    public boolean beenLiked(User user){
        return Like.dao.hasLike(this, user) != null;
    }
    public boolean beenFavod(User user){
        return Favorite.dao.hasFavo(this, user) != null;
    }

    public boolean equals(Object model) {
        return model != null && this.getClass().equals(model.getClass()) && ((XModel) model).getId() == this.getId();
    }
}
